package com.tree.backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tree.backend.common.Result;
import com.tree.backend.entity.SignalCollection;
import com.tree.backend.service.ISignalCollectionService;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 信号数据采集表 前端控制器
 * </p>
 *
 * @author tree
 * @since 2025-10-24
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/signalCollection")
public class SignalCollectionController {

    private final ISignalCollectionService signalCollectionService;

    /**
     * 获取信号采集列表（分页+搜索）
     */
    @GetMapping("/list")
    public Result<IPage<SignalCollection>> getSignalCollectionList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer deviceId,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {

        Page<SignalCollection> pageParam = new Page<>(page, size);
        QueryWrapper<SignalCollection> queryWrapper = new QueryWrapper<>();

        if (deviceId != null) {
            queryWrapper.eq("device_id", deviceId);
        }
        if (StringUtils.hasText(startTime)) {
            queryWrapper.ge("collect_time", startTime);
        }
        if (StringUtils.hasText(endTime)) {
            queryWrapper.le("collect_time", endTime);
        }

        queryWrapper.orderByDesc("collect_time");
        IPage<SignalCollection> signalPage = signalCollectionService.page(pageParam, queryWrapper);

        return Result.success(signalPage);
    }

    /**
     * 获取信号采集详情
     */
    @GetMapping("/{id}")
    public Result<SignalCollection> getSignalCollectionDetail(@PathVariable Integer id) {
        SignalCollection signalCollection = signalCollectionService.getById(id);
        if (signalCollection == null) {
            return Result.error(401, "信号采集记录不存在");
        }
        return Result.success(signalCollection);
    }

    /**
     * 添加信号采集记录
     */
    @PostMapping
    public Result<String> addSignalCollection(@RequestBody SignalCollection signalCollection) {
        boolean success = signalCollectionService.save(signalCollection);
        return success ? Result.success("添加信号采集记录成功") : Result.error(401, "添加信号采集记录失败");
    }

    /**
     * 更新信号采集记录
     */
    @PutMapping("/{id}")
    public Result<String> updateSignalCollection(@PathVariable Integer id, @RequestBody SignalCollection signalCollection) {
        signalCollection.setId(id);
        boolean success = signalCollectionService.updateById(signalCollection);
        return success ? Result.success("更新信号采集记录成功") : Result.error(401, "更新信号采集记录失败");
    }

    /**
     * 删除信号采集记录
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteSignalCollection(@PathVariable Integer id) {
        boolean success = signalCollectionService.removeById(id);
        return success ? Result.success("删除信号采集记录成功") : Result.error(401, "删除信号采集记录失败");
    }

    /**
     * 批量删除信号采集记录
     */
    @DeleteMapping("/batch")
    public Result<String> batchDeleteSignalCollections(@RequestParam List<Integer> ids) {
        boolean success = signalCollectionService.removeByIds(ids);
        return success ? Result.success("批量删除信号采集记录成功") : Result.error(401, "批量删除信号采集记录失败");
    }

    /**
     * 获取信号统计信息
     */
    @GetMapping("/stats")
    public Result<Object> getSignalStats() {
        // 统计总记录数
        long totalCount = signalCollectionService.count();

        // 获取最新信号数据
        QueryWrapper<SignalCollection> latestWrapper = new QueryWrapper<>();
        latestWrapper.orderByDesc("collect_time").last("LIMIT 1");
        SignalCollection latestSignal = signalCollectionService.getOne(latestWrapper);

        // 获取信号强度平均值
        QueryWrapper<SignalCollection> avgWrapper = new QueryWrapper<>();
        avgWrapper.select("AVG(signal_strength) as avgSignalStrength");
        Map<String, Object> avgResult = signalCollectionService.getMap(avgWrapper);
        BigDecimal Strength = avgResult != null && avgResult.get("avgSignalStrength") != null
            ? (BigDecimal) avgResult.get("avgSignalStrength") 
            : BigDecimal.ZERO;

        // 返回统计信息
        return Result.success(new Object() {
            public final long total = totalCount;
            public final SignalCollection latest = latestSignal;
            public final BigDecimal avgSignalStrength = Strength;
        });
    }

    /**
     * 获取设备信号趋势数据
     */
    @GetMapping("/trend/{deviceId}")
    public Result<List<SignalCollection>> getDeviceSignalTrend(
            @PathVariable Integer deviceId,
            @RequestParam(defaultValue = "7") Integer days) {
        
        LocalDateTime startTime = LocalDateTime.now().minusDays(days);
        QueryWrapper<SignalCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_id", deviceId)
                   .ge("collect_time", startTime)
                   .orderByAsc("collect_time");
        
        List<SignalCollection> trendData = signalCollectionService.list(queryWrapper);
        return Result.success(trendData);
    }

    /**
     * 随机插入设备信号数据
     */
    @PostMapping("/random")
    public Result<String> addRandomSignalData(@RequestParam(defaultValue = "5") Integer count) {
        try {
            // 获取现有设备ID列表
            List<Integer> deviceIds = signalCollectionService.getDeviceIds();
            if (deviceIds.isEmpty()) {
                return Result.error(401, "没有可用的设备ID");
            }

            int successCount = 0;
            for (int i = 0; i < count; i++) {
                // 随机选择一个设备ID
                int randomIndex = (int) (Math.random() * deviceIds.size());
                Integer deviceId = deviceIds.get(randomIndex);

                // 创建随机信号数据
                SignalCollection randomSignal = new SignalCollection();
                randomSignal.setDeviceId(deviceId);
                randomSignal.setSignalStrength(BigDecimal.valueOf(-60 - Math.random() * 60)); // -60到-120 dBm
                randomSignal.setSnrRatio(BigDecimal.valueOf(10 + Math.random() * 20)); // 10到30 dB
                randomSignal.setBandwidth((int) (20 + Math.random() * 80)); // 20到100 MHz
                randomSignal.setLatency((int) (10 + Math.random() * 190)); // 10到200 ms
                randomSignal.setPacketLoss(BigDecimal.valueOf(Math.random() * 5)); // 0到5%
                randomSignal.setCollectTime(LocalDateTime.now().minusMinutes((long) (Math.random() * 1440))); // 24小时内随机时间

                boolean success = signalCollectionService.save(randomSignal);
                if (success) {
                    successCount++;
                }
            }

            return Result.success("成功采集 " + successCount + " 条信号数据");
        } catch (Exception e) {
            return Result.error(500, "插入随机数据失败: " + e.getMessage());
        }
    }
}
